import React, { useState, useRef, useEffect } from 'react';

interface AudioRecorderProps {
  uploadUrl: string;
  recordId: string;
  chunkDuration?: number;
  onStatusChange?: (status: 'idle' | 'recording' | 'stopped' | 'error') => void;
  onError?: (error: string) => void;
  onTranscript?: (transcript: string) => void;
}

const AudioRecorder: React.FC<AudioRecorderProps> = ({
  uploadUrl,
  recordId,
  chunkDuration = 5000,
  onStatusChange,
  onError,
  onTranscript
}) => {
  const [isRecording, setIsRecording] = useState(false);
  const [status, setStatus] = useState<'idle' | 'recording' | 'stopped' | 'error'>('idle');
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const audioStreamRef = useRef<MediaStream | null>(null);
  const chunkIndexRef = useRef(0);

  // 组件卸载时清理资源
  useEffect(() => {
    return () => {
      cleanupResources();
    };
  }, []);

  const cleanupResources = () => {
    // 停止mediaRecorder
    if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
      try {
        mediaRecorderRef.current.stop();
      } catch (error) {
        console.warn('停止MediaRecorder时出错:', error);
      }
    }
    
    // 停止所有音频轨道
    if (audioStreamRef.current) {
      audioStreamRef.current.getTracks().forEach(track => {
        try {
          track.stop();
        } catch (error) {
          console.warn('停止音频轨道时出错:', error);
        }
      });
      audioStreamRef.current = null;
    }
    
    // 重置状态
    mediaRecorderRef.current = null;
    chunkIndexRef.current = 0;
  };

  const updateStatus = (newStatus: 'idle' | 'recording' | 'stopped' | 'error') => {
    setStatus(newStatus);
    setIsRecording(newStatus === 'recording');
    onStatusChange?.(newStatus);
  };

  const startRecording = async () => {
    try {
      // 获取麦克风权限
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      audioStreamRef.current = stream;
      
      // 创建MediaRecorder实例
      const mediaRecorder = new MediaRecorder(stream, { 
        mimeType: 'audio/webm;codecs=opus'
      });
      mediaRecorderRef.current = mediaRecorder;
      chunkIndexRef.current = 0;

      // 设置分片回调
      mediaRecorder.ondataavailable = async (event) => {
        if (event.data.size > 0) {
          await uploadAudioChunk(event.data);
          chunkIndexRef.current++;
        }
      };

      mediaRecorder.onstop = () => {
        // 清理资源
        if (audioStreamRef.current) {
          audioStreamRef.current.getTracks().forEach(track => {
            try {
              track.stop();
            } catch (error) {
              console.warn('停止音频轨道时出错:', error);
            }
          });
          audioStreamRef.current = null;
        }
        updateStatus('stopped');
      };

      mediaRecorder.onerror = (event) => {
        console.error('录音错误:', event);
        updateStatus('error');
        onError?.('录音过程中发生错误');
      };

      // 开始录音，按指定时间分片
      mediaRecorder.start(chunkDuration);
      updateStatus('recording');
    } catch (error: any) {
      console.error('获取麦克风权限失败:', error);
      updateStatus('error');
      onError?.(`无法访问麦克风，请检查权限设置: ${error.message || error}`);
    }
  };

  const stopRecording = () => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop();
      // cleanupResources将在mediaRecorder的onstop事件中被调用
    }
  };

  const uploadAudioChunk = async (blob: Blob) => {
    try {
      console.log(`正在上传音频分片 ${chunkIndexRef.current} 到 ${uploadUrl}`);
      console.log(`音频分片大小: ${blob.size} 字节`);
      
      const formData = new FormData();
      formData.append('recordId', recordId);
      formData.append('chunkIndex', chunkIndexRef.current.toString());
      formData.append('audio', blob, `audio-${chunkIndexRef.current}.webm`);

      const response = await fetch(uploadUrl, {
        method: 'POST',
        body: formData
      });

      console.log(`上传响应状态: ${response.status} ${response.statusText}`);
      console.log('响应头:', response.headers);

      if (!response.ok) {
        throw new Error(`上传失败: ${response.status} ${response.statusText}`);
      }

      // 检查响应体是否为空
      const responseText = await response.text();
      console.log('响应体文本:', responseText);
      
      if (!responseText) {
        throw new Error('服务器返回了空的响应体');
      }

      // 尝试解析JSON
      let result;
      try {
        result = JSON.parse(responseText);
      } catch (parseError: any) {
        throw new Error(`服务器返回了无效的JSON格式: ${parseError.message || parseError}`);
      }
      
      console.log('上传响应结果:', result);
      
      // 检查result是否为有效对象
      if (!result || typeof result !== 'object') {
        throw new Error('服务器返回了无效的响应格式');
      }
      
      if (result.success === false) {
        throw new Error(result.message || '上传失败');
      }
      
      // 如果后端返回了语音转文字的结果，将其传递给父组件
      // 检查recognizedText字段（后端实际使用的字段）
      if (result.recognizedText && typeof result.recognizedText === 'string') {
        onTranscript?.(result.recognizedText);
      }
      // 也检查transcript字段（为了兼容性）
      else if (result.transcript && typeof result.transcript === 'string') {
        onTranscript?.(result.transcript);
      }
      
      console.log(`音频分片 ${chunkIndexRef.current} 上传成功`);
    } catch (error: any) {
      console.error('上传音频分片失败:', error);
      onError?.(`上传音频分片失败: ${error.message || error}`);
    }
  };

  return (
    <div className="audio-recorder">
      <div className="recording-status">
        状态: 
        {status === 'idle' && '未开始'}
        {status === 'recording' && '录音中...'}
        {status === 'stopped' && '已停止'}
        {status === 'error' && '错误'}
      </div>
      <div className="recording-controls">
        {!isRecording ? (
          <button 
            onClick={startRecording} 
            className="record-button"
          >
            开始录音
          </button>
        ) : (
          <button 
            onClick={stopRecording} 
            className="stop-record-button"
          >
            停止录音
          </button>
        )}
      </div>
    </div>
  );
};

export default AudioRecorder;